#include <iostream>
#include <unistd.h>
#include <string>
#include <cstring>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include "Thread.hpp"
#include "Log.hpp"

using namespace log_ns;
using namespace ThreadMoudle;

int ClientInit()
{
    int sockfd = ::socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        LOG(FATAL, "socket error\n");
        exit(1);
    }
    LOG(DEBUG, "socket create success, sockfd:%d\n", sockfd);

    return sockfd;
}

void SendMessage(int sockfd, std::string server_ip, uint16_t server_port, std::string name)
{

    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(server_port);
    server.sin_addr.s_addr = inet_addr(server_ip.c_str());

    while (true)
    {
        std::string msg;
        std::cout << name + "# ";
        std::getline(std::cin, msg);
        sendto(sockfd, msg.c_str(), msg.size(), 0, (struct sockaddr *)&server, sizeof(server));
    }
}

void RecvMessage(int sockfd, std::string name)
{
    while (true)
    {
        struct sockaddr_in temp;
        socklen_t len = sizeof(temp);
        char buff[1024];
        int n = recvfrom(sockfd, buff, sizeof(buff) - 1, 0, (struct sockaddr *)&temp, &len);
        if (n > 0)
        {
            buff[n] = 0;
            std::cout << name + "# " << buff << std::endl;
        }
        else
        {
            LOG(DEBUG,"recvfrom error\n");
            //break;
        }
    }
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cerr << "Usage " << argv[0] << " Server-ip Server-port" << std::endl;
        exit(0);
    }

    std::string server_ip = argv[1];
    uint16_t server_port = std::stoi(argv[2]);
    int sockfd = ClientInit();

    Thread sender("send-thread", std::bind(&SendMessage, sockfd, server_ip, server_port, std::placeholders::_1));
    Thread recver("recv-thread", std::bind(&RecvMessage, sockfd, std::placeholders::_1));

    sender.start();
    recver.start();

    sender.join();
    recver.join();

    // // client的端口号一般由client的OS随机选择
    // // client不需要“显示”地绑定IP和端口号，当client第一次给服务器发消息时OS会自动绑定IP和端口号
    // while (true)
    // {
    //     std::string msg;
    //     std::getline(std::cin, msg);
    //     int n = sendto(sockfd, msg.c_str(), msg.size(), 0, (struct sockaddr *)&server, sizeof(server));
    //     if (n > 0)
    //     {
    //         struct sockaddr_in temp;
    //         socklen_t len = sizeof(temp);
    //         char buff[1024];
    //         int m = recvfrom(sockfd, buff, sizeof(buff) - 1, 0, (struct sockaddr *)&temp, &len);
    //         if (m > 0)
    //         {
    //             buff[m] = 0;
    //             std::cout << buff << std::endl;
    //         }
    //         else
    //         {
    //             break;
    //         }
    //     }
    // }

    // ::close(sockfd);
    return 0;
}